package kz.home;

import db.CityFilter;
import kz.home.obj.City;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 * <strong>title</strong>
 * <p> describe
 *
 * @author: Danik <br>
 * Date: 15.07.2009  <br>
 * Time: 12:24:21  <br>
 */
public class SomeMidlet extends MIDlet implements CommandListener{
    private City[] cities;
    private static final String DB = "Cities";
    private Command cmd_exit;
    private Command cmd_add;
    private Command cmd_read;
    private Command cmd_delete;
    private Command cmd_filter;
    protected Form main;


    protected void startApp() {
        main = new Form("Some Midlet");
        main.setCommandListener(this);
        //
        Display.getDisplay(this).setCurrent(main);

        cmd_exit = new Command("Exit",      Command.EXIT, 1);
        cmd_add = new Command("Добавить",   Command.EXIT, 2);
        cmd_read = new Command("Прочитать", Command.SCREEN, 3);
        cmd_delete = new Command("Удалить", Command.SCREEN, 4);
        cmd_filter = new Command("Фильтр",  Command.SCREEN, 5);

        main.addCommand(cmd_exit);
        main.addCommand(cmd_add);
        main.addCommand(cmd_read);
        main.addCommand(cmd_delete);
        main.addCommand(cmd_filter);
    }

    private void store() {
        RecordStore store = null;
        try {
            store = RecordStore.openRecordStore(DB, true);

            for (int i = 0; i < cities.length; i++) {
                byte[] record = cities[i].getRecord();
                store.addRecord(record, 0, record.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (store != null) store.closeRecordStore();
            } catch (RecordStoreException e) { /**/ }
        }
    }

    private void init() {
        City city_1 = new City("1", "Алматы", "есть", null, null, null);
        City city_2 = new City("2", "Астана", "есть", null, null, null);
        City city_3 = new City("3", "Уральск", "нет", null, null, null);

        cities = new City[]{city_1, city_2, city_3};
    }

    protected void pauseApp() {

    }

    protected void destroyApp(boolean b) throws MIDletStateChangeException {

    }

    protected City[] readStore() {
        RecordStore store = null;

        try {
            store = RecordStore.openRecordStore(DB, false);

            City[] cities = new City[store.getNumRecords()];

            System.out.println("cities count = [" + cities.length + "]");
            System.out.println("Num Record[" + store.getNumRecords() + "]");
            
            for (int i = 1; i <= store.getNumRecords(); i++) {
                byte[] seed = store.getRecord(i);
                City city = City.getCity(seed);
                System.out.println("i[" + i + "] id[" + city.getId() + "]");
                cities[i - 1] = city;
            }

            displayCities(cities);
        } catch (RecordStoreException e) {
            e.printStackTrace();
        } finally {
            if (store != null) {
                try {
                    store.closeRecordStore();
                } catch (RecordStoreException e) { /*e.printStackTrace();*/ }
            }
        }
        return cities;
    }

    private void displayCities(City[] cities) {
        List list = new List("Cities", List.IMPLICIT);

        for (int i = 0; i < cities.length; i++) {
            if (cities[i] == null) {
                System.out.println("i{" + i + "} = null");
                continue;

            }
            list.append("id [" + cities[i].getId() + "] "
                    + "name [" + cities[i].getName() + "] "
                    + "state [" + cities[i].getState() + "] "
                    , null);

        }

        Display.getDisplay(this).setCurrent(list);
    }

    private void filter() {
        final Form form_filter = new Form("Filter");
        final TextField field = new TextField("id", null, 5, TextField.ANY);
        form_filter.append(field);

        final Command doFilter = new Command("Do filter",Command.OK, 1);
        form_filter.addCommand(doFilter);

        form_filter.setCommandListener(new CommandListener() {
            public void commandAction(Command command, Displayable displayable) {
                if (displayable == form_filter) {
                    if (command == doFilter) {
                        System.out.println("text[" + field.getString() + "]");
                        doFilter(field.getString().trim());
                    }
                }
            }
        });

        Display.getDisplay(this).setCurrent(form_filter);

    }

    protected void doFilter(String id) {
        CityFilter filter = new CityFilter(id);
        City[] _cities = new City[1];
        RecordStore store = null;

        try {
            store = RecordStore.openRecordStore(DB, false);
            RecordEnumeration re = store.enumerateRecords(filter, null, false);

            while (re.hasNextElement()) {
                _cities[0] = City.getCity(re.nextRecord());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (store != null) store.closeRecordStore();
            } catch (RecordStoreException e) {
                e.printStackTrace();
            }
        }

        displayCities(_cities);
    }

    public void commandAction(Command command, Displayable displayable) {
        if (displayable == main) {
            if (command == cmd_add) {
                init();
                store();
            }

            if (command == cmd_read) {
                System.out.println("cmd_read");
                readStore();
            }

            if (command == cmd_delete) {
                try {
                    RecordStore.deleteRecordStore(DB);
                    System.out.println("db has been deleted [" + DB + "]");
                } catch (RecordStoreException e) {
                    System.out.println("there is no such db[" +DB+ "] ");
                }
            }

            if (command == cmd_exit) {
                System.out.println("exit");

            }

            if (command == cmd_filter) {
                filter();
            }
        }
    }
}
